#!/use/bin/python
# coding=utf-8
# 数据分析-睡觉提醒-服务完成情况
import datetime
import pymysql

from dbutils.pooled_db import PooledDB


# proactive_service_conf 数据源
def getConfConnection():
    # 开发环境
    # pool = PooledDB(pymysql, 1, host='172.20.135.96', user='pushdb', passwd='SkYWOrTh$TcOs',
    #                db='proactive_service_conf',
    #                port=3306)  # 1为连接池里的最少连接数
    # 测试环境
    pool = PooledDB(pymysql, 1, host='172.20.150.109', user='test_dmp', passwd='DghHC3lFM1KzT3ZJ',
                db='proactive_service_conf', port=3307)  # 1为连接池里的最少连接数
    # pool = PooledDB(pymysql,1,host='127.0.0.1',user='root',passwd='root',db='life_assistant_data',port=3306) # 5为连接池里的最少连接数
    conn = pool.connection()
    cur = conn.cursor()
    return conn, cur

# proactive_service_data 数据源
def getDataConnection():
    # 开发环境
    #pool = PooledDB(pymysql, 1, host='172.20.151.80', user='pushdb', passwd='SkYWOrTh$TcOs',
    #                db='proactive_service_data',port=3306)  # 1为连接池里的最少连接数

    # 测试环境
    pool = PooledDB(pymysql, 1, host='172.20.154.103', user='test_dmp', passwd='DghHC3lFM1KzT3ZJ',
                    db='proactive_service_data', port=3407)  # 1为连接池里的最少连接数
    # pool = PooledDB(pymysql,1,host='127.0.0.1',user='root',passwd='root',db='life_assistant_data',port=3306) # 5为连接池里的最少连接数
    conn = pool.connection()
    cur = conn.cursor()
    return conn, cur

#根据传入的SQL 返回执行SQL返回的数量
def selectNumBySql(sql,conf=2):
    if conf == 1:
        conn, cur = getConfConnection()
    else:
        conn, cur = getDataConnection()
    #print(sql)
    cur.execute(sql)
    numResult = cur.fetchone()
    num = 0
    if numResult is not None:
        num = numResult[0]
    return num


#根据月份 获取本月指定指标的 总和
#tableName 指定的报表
#columnName 指定的指标字段
#date 月份
def getSumNumByTableColumnNameAndDate(tableName,columnName,date):
    conn, cur = getDataConnection()
    selectNumSql = f"""
                     select sum({columnName}) from {tableName} t where 1=1   
                     """;
    if len(date) >0:
        selectNumSql = f"""{selectNumSql} and SUBSTR( t.ref_date, 1,7) = '{date}' and LENGTH(t.ref_date) = 10  """
    cur.execute(selectNumSql)
    #print(selectNumSql);
    numResult = cur.fetchone()
    num = 0
    if numResult!= None:
        num = numResult[0]
    if num is None:
        return 0
    return num

#计算百分比 保留两位小数  如:34.88%
# X为分子 Y为分母
def getRateByXY(X,Y):
    rate = 0
    if(X is None or Y is None):
        return rate
    if Y != 0:
        if X > Y:
            rate = 100
        else:
            rate = round(X / Y, 4) * 100
    return rate

#数据分析-睡觉提醒-服务完成情况
def insertCompleteRate(date):
    try:
        conn, cur = getDataConnection()
        #判断 analysis_sjtx_complete_rate 表是否已经存在当天 数据
        countNum = selectNumBySql(f"select count(1) num from analysis_sjtx_complete_rate t where 1=1  and t.ref_date =  '{date}'")
        # 获取当日睡觉提醒 弹窗数量
        pushNum = selectNumBySql(
            f"select count(DISTINCT(t.active_id)) from log_common_service_{yyMMddDate} t where t.`key` = 'srShowResult'  and JSON_EXTRACT(msg,'$.result') =1")
        # 获取所有睡觉提醒 弹窗数量
        pushAllNum = selectNumBySql(
            f"select ifnull(sum(service_num),0) from analysis_sjtx_complete_rate t where 1=1 and LENGTH(t.ref_date) = 10 and  t.ref_date <= '{date}' ")
        # 获取收到弹窗后-弹窗自动消失数量
        autoExpireNum = selectNumBySql(
            f"select count(DISTINCT(t.active_id)) from log_common_service_{yyMMddDate} t where t.`key` = 'srShowAfterOperate'  and JSON_EXTRACT(msg,'$.choose') =3")
        # 获取收到弹窗后-选择"知道了吗"数量
        cancelNum = selectNumBySql(
            f"select count(DISTINCT(t.active_id)) from log_common_service_{yyMMddDate} t where t.`key` = 'srShowAfterOperate'  and JSON_EXTRACT(msg,'$.choose') =1")
        # 获取收到弹窗后-选择"助眠功能"数量
        toZmgnNum = selectNumBySql(
            f"select count(DISTINCT(t.active_id)) from log_common_service_{yyMMddDate} t where t.`key` = 'srShowAfterOperate'  and JSON_EXTRACT(msg,'$.choose') =2")
        toZmgnRate = getRateByXY(toZmgnNum, pushNum)
        # 获取 当日 收到睡觉提醒弹窗 15分钟内关机的设备量
        close15MinNum = selectNumBySql(
            f"""
            select count(DISTINCT(t.active_id)) from log_common_service_{yyMMddDate} t where t.`key` in ('srShowAfterScreenOff') 
                and JSON_EXTRACT(t.msg,'$.interval') >0 and JSON_EXTRACT(t.msg,'$.interval') <= 15*60*1000
        """)
        # 获取 当日 收到睡觉提醒弹窗 30分钟内关机的设备量
        close30MinNum = selectNumBySql(
            f"""
            select count(DISTINCT(t.active_id)) from log_common_service_{yyMMddDate} t where t.`key` in ('srShowAfterScreenOff') 
                and JSON_EXTRACT(t.msg,'$.interval') >15*60*1000 and JSON_EXTRACT(t.msg,'$.interval') <= 30*60*1000
        """)
        # 获取收到睡觉提醒弹窗 15/30分钟关闭电视量及成功率
        success15MinRate = getRateByXY(close15MinNum,pushNum)
        success30MinRate = getRateByXY(close30MinNum,pushNum)
        if countNum == 0:
            logDetail = f"{date}日新增-睡觉提醒弹窗数量为{pushNum},总量为{pushAllNum},弹窗自动消失次数{autoExpireNum},选择知道了吗次数为{cancelNum},选择助眠功能次数为{toZmgnNum},比例为{toZmgnRate}," \
                        f" 15分钟内关闭数为{close15MinNum},15分钟内关机成功率为{success15MinRate},30分钟内关闭数为{close30MinNum},30分钟内关机成功率为{success30MinRate}"
            print(logDetail)
            # 插入早间服务可见设备量
            insertSql = f"""insert into analysis_sjtx_complete_rate(service_num,service_cumulate_num,auto_expire_num,cancel_num,to_zmgn_num,to_zmgn_rate,close_15min_num,close_30min_num
            ,success_15min_rate,success_30min_rate,ref_date) 
                value({pushNum},{pushAllNum},{autoExpireNum},{cancelNum},{toZmgnNum},{toZmgnRate},{close15MinNum},{close30MinNum},{success15MinRate},{success30MinRate},'{date}')"""
            cur.execute(insertSql)
        else:
            logDetail = f"{date}日更新-睡觉提醒弹窗数量为{pushNum},总量为{pushAllNum},弹窗自动消失次数{autoExpireNum},选择知道了吗次数为{cancelNum},选择助眠功能次数为{toZmgnNum},比例为{toZmgnRate}," \
                        f" 15分钟内关闭数为{close15MinNum},15分钟内关机成功率为{success15MinRate},30分钟内关闭数为{close30MinNum},30分钟内关机成功率为{success30MinRate}"
            print(logDetail)
            # 更新早间服务可见设备量
            updateSql = f"""
                update analysis_sjtx_complete_rate set service_num = {pushNum} ,service_cumulate_num = {pushAllNum},auto_expire_num ={autoExpireNum},cancel_num={cancelNum},to_zmgn_num={toZmgnNum},to_zmgn_rate={toZmgnRate},
                close_15min_num = {close15MinNum} ,close_30min_num = {close30MinNum} ,success_15min_rate = {success15MinRate},success_30min_rate = {success30MinRate} , update_time = now()  where
                    ref_date = '{date}' 
            """
            cur.execute(updateSql)
        saveLog(logDetail, date)
        conn.commit()
    except Exception as e:
        print(e)
    finally:
        cur.close()
        conn.close()


# 记录 数据分析-睡觉提醒-服务完成情况  --  月度
def insertCompleteRateMonth(toMonthDay):
    try:
        conn, cur = getDataConnection()
        #判断 analysis_sjtx_complete_rate 表是否已经存在当天 数据
        countNum = selectNumBySql(f"select count(1) num from analysis_sjtx_complete_rate t where 1=1  and t.ref_date =  '{toMonthDay}'")
        # 计算本月的新增弹窗数据量
        pushNum  = getSumNumByTableColumnNameAndDate('analysis_sjtx_complete_rate', 'service_num', toMonthDay)
        # 获取所有睡觉提醒 弹窗数量
        pushAllNum = selectNumBySql(
            f"select sum(service_num) from analysis_sjtx_complete_rate t where 1=1 and LENGTH(t.ref_date) = 10  ")
        # 获取 本月 收到睡觉提醒弹窗 15分钟内关机的设备量
        close15MinNum = getSumNumByTableColumnNameAndDate('analysis_sjtx_complete_rate', 'close_15min_num', toMonthDay)
        # 获取 本月 收到睡觉提醒弹窗 30分钟内关机的设备量
        close30MinNum = getSumNumByTableColumnNameAndDate('analysis_sjtx_complete_rate', 'close_30min_num', toMonthDay)
        # 本月获取收到睡觉提醒弹窗 15/30分钟关闭电视量及成功率
        success15MinRate = getRateByXY(close15MinNum, pushNum)
        success30MinRate = getRateByXY(close30MinNum, pushNum)

        if countNum == 0:
            logDetail = f"{toMonthDay}月新增-睡觉提醒弹窗数量为{pushNum},总量为{pushAllNum},15分钟内关闭数为{close15MinNum},15分钟内关机成功率为{success15MinRate},30分钟内关闭数为{close30MinNum},30分钟内关机成功率为{success30MinRate}"
            print(logDetail)
            # 插入早间服务可见设备量
            insertSql = f"""insert into analysis_sjtx_complete_rate(service_num,service_cumulate_num,close_15min_num,close_30min_num
            ,success_15min_rate,success_30min_rate,ref_date) 
                value({pushNum},{pushAllNum},{close15MinNum},{close30MinNum},{success15MinRate},{success30MinRate},'{toMonthDay}')"""
            cur.execute(insertSql)
        else:
            logDetail = f"{toMonthDay}月更新-睡觉提醒弹窗数量为{pushNum},总量为{pushAllNum},15分钟内关闭数为{close15MinNum},15分钟内关机成功率为{success15MinRate},30分钟内关闭数为{close30MinNum},30分钟内关机成功率为{success30MinRate}"
            print(logDetail)
            # 更新早间服务可见设备量
            updateSql = f"""
                update analysis_sjtx_complete_rate set service_num = {pushNum} ,service_cumulate_num = {pushAllNum},close_15min_num = {close15MinNum} ,close_30min_num = {close30MinNum} ,
                success_15min_rate = {success15MinRate},success_30min_rate = {success30MinRate} , update_time = now()  where
                    ref_date = '{toMonthDay}' 
            """
            cur.execute(updateSql)
        saveLog(logDetail, toMonthDay)
        conn.commit()
    except Exception as e:
        print(e)
    finally:
        cur.close()
        conn.close()

# 获取当前日期
def todayYMD():
    today = datetime.datetime.now()-1
    # 获取想要的日期的时间
    re_date = (today).strftime('%Y-%m-%d')
    return re_date


# 获取前1天或N天的日期，beforeOfDay=1：前1天；beforeOfDay=N：前N天
def getdate(beforeOfDay):
    today = datetime.datetime.now()
    # 计算偏移量
    offset = datetime.timedelta(days=-beforeOfDay)
    # 获取想要的日期的时间
    re_date = (today + offset).strftime('%Y-%m-%d')
    return re_date

# 获取前1天或N天的日期，beforeOfDay=1：前1天；beforeOfDay=N：前N天
def getMonthdate(beforeOfDay):
    today = datetime.datetime.now()
    # 计算偏移量
    offset = datetime.timedelta(days=-beforeOfDay)
    # 获取想要的日期的时间
    re_date = (today + offset).strftime('%Y-%m')
    return re_date

#如 2022年12月13号 获取 221213 作为分表后缀
def getdateyyMMdd(beforeOfDay):
    today = datetime.datetime.now()
    # 计算偏移量
    offset = datetime.timedelta(days=-beforeOfDay)
    # 获取想要的日期的时间
    re_date = (today + offset).strftime('%Y%m%d')
    re_date = re_date[2:]
    return re_date

def saveLog(detail,ref_date):
    try:
        conn, cur = getDataConnection()
        jobId = 31
        jobName = '核心指标-睡觉提醒-推送成功率'
        tableName = 'analysis_sjtx_complete_rate'
        # 插入日志表
        saveLogSql = """insert into log_xxljob_analysis (job_id,job_name,detail,table_name,ref_date) 
                value(%s,'%s','%s','%s','%s')""" % (jobId,jobName,detail,tableName,ref_date)
        cur.execute(saveLogSql)
        conn.commit()
    except Exception as e:
        print(e)
    finally:
        cur.close()
        conn.close()

if __name__ == '__main__':
    d = 1
    date = getdate(d)
    yyMMddDate = getdateyyMMdd(d)
    monthdate = getMonthdate(d)
    print (f"{date}日期,执行<数据分析-睡觉提醒-服务完成情况>报表")
    insertCompleteRate(date)
    insertCompleteRateMonth(monthdate)
